﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Tb.App.API.Applications.Command.DeepProcessing;
using Tb.App.Domain.Rabbit.DeepProcessing;
using Tb.App.ErrorCode;
using Tb.App.Infrastructure.Interfaces;

namespace Tb.App.API.Applications.CommandHandler.DeepProcessing
{
    /// <summary>
    /// 添加深加工信息-处理
    /// </summary>
    public class AddDeeprocessingModelCommandHandler : IRequestHandler<AddDeeprocessingModelCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<DeepProcessingModel> deeprocessingModelRep;
        private readonly ILogger<AddDeeprocessingModelCommandHandler> logger;
        private readonly IMapper mapper;

        public AddDeeprocessingModelCommandHandler(IBaseRepository<DeepProcessingModel> deeprocessingModelRep,ILogger<AddDeeprocessingModelCommandHandler> logger,IMapper mapper)
        {
            this.deeprocessingModelRep = deeprocessingModelRep;
            this.logger = logger;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(AddDeeprocessingModelCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result=new ApiResult<int>();
           
           var executionStrategy= deeprocessingModelRep.DB.Database.CreateExecutionStrategy();
            await executionStrategy.ExecuteAsync(async () =>
            {
                using (var tran =await deeprocessingModelRep.DB.Database.BeginTransactionAsync()) 
                {
                    try
                    {
                        var list = await deeprocessingModelRep.GetAll().Where(x => !x.IsDel && x.Batch == request.Batch).ToListAsync();
                        list.ForEach(o =>
                        {
                            o.IsDel = true;
                        });
                        await deeprocessingModelRep.UpdateRange(list);

                        var entity = mapper.Map<DeepProcessingModel>(request);
                        var a= await deeprocessingModelRep.AddAsync(entity);
                        if (a > 0)
                        {
                            result.Code = ApiEnum.添加成功;
                            result.Message = "添加成功";
                            result.Data = a;
                        }
                        else
                        {
                            result.Code = ApiEnum.添加失败;
                            result.Message = "添加失败";
                            result.Data = a;
                        }
                        await tran.CommitAsync(cancellationToken);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError("添加深加工信息异常"+ex.Message);
                        result.Code = ApiEnum.添加失败;
                        result.Message = "添加失败"+ex.Message;
                        await tran.RollbackAsync(cancellationToken);
                        throw;
                    }
                }
            });
            return result;
        }
    }
}
